#!/bin/bash
#
#

functionname="$1"

function formatresult(){
	code="$1"
	message="$2"
	if [ -z "$message" ];then
		message="unknown error"
	fi
	echo "{\"functionname\":\"${functionname}\",\"code\":\"${code}\",\"message\":\"${message}\",}"
	exit 0
}

function execcmd(){
	cmd="$1"
	message=$(${cmd} 2>&1)
	code=$?
	formatresult "${code}" "${message}"
}

code=0
message="success"


function ret(){
code=$1
message="$2"
if [ "$code" != "0" ];then
	formatresult "${code}" "${message}"
fi
}

screenlog="/var/log/screenlog/%t.log"
screenconf="/etc/screenrc"

which screen &>/dev/null
if [ $? -ne 0 ];then
	yum install -y screen &>/dev/null
	code=$?
	if [ $code -ne 0 ];then
		ret $code "install screen failed"
	fi
fi

if [ ! -d $(dirname "${screenlog}") ];then
	mkdir -p $(dirname "/var/log/screenlog/%t.log")
	ret $? "create screen log dir failed"
fi

grep "logfile ${screenlog}" $screenconf &>/dev/null
if [ $? -ne 0 ];then
	sed -i "/^logfile/d" ${screenconf}
	sed -i "\$alogfile ${screenlog}" ${screenconf}
	ret $? "add screen logconf failed"
fi
formatresult "${code}" "${message}"